/**
 * 强制拍照
 * Created by WMM on 2018/06/18.
 */
import { Component, ElementRef } from '@angular/core';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { ImagePicker } from "@ionic-native/image-picker";
import { IonicPage, NavController, ToastController, ActionSheetController, NavParams, AlertController, LoadingController } from 'ionic-angular';
import { ApiHost } from '../../api/Constants';

@IonicPage()
@Component({
  selector: 'page-forced-photo',
  templateUrl: 'forced-photo.html'
})
export class ForcedPhoto {
  private imgData: string = "assets/imgs/photo.jpg";
  private planPositionId: string;
  private qrcode: string;
  private bizType: number;
  private fileTransfer: FileTransferObject = this.transfer.create();
  private photoNumber: number;
  private disTag: boolean;
  //这里标识false为只有装货 true为装卸货都有可能(可能出现2种情况)
  private bizTag: boolean;

  constructor(public navCtrl: NavController, private loadingCtrl: LoadingController, private transfer: FileTransfer, public actionSheetCtrl: ActionSheetController, public params: NavParams, private toastCtrl: ToastController, public imagePicker: ImagePicker, private camera: Camera) {
    this.qrcode = params.get("qrcode");
    this.planPositionId = params.get("planPositionId");
    this.photoNumber = 0;
    this.bizType = 10;
    this.bizTag = params.get("bizTag");
    this.disTag = true;
  }


  /**
   * 打开摄像头拍照
   */
  takePhoto() {
    const options: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.DATA_URL,        //DATA_URL 是 base64   FILE_URL 是文件路径
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum: true,                                       //是否保存到相册
      // sourceType: this.camera.PictureSourceType.CAMERA ,         //是打开相机拍照还是打开相册选择  PHOTOLIBRARY : 相册选择, CAMERA : 拍照,
    }
    this.camera.getPicture(options).then((imageData) => {
      let base64Image = 'data:image/jpeg;base64,' + imageData;
      this.imgData = base64Image;
      this.disTag = false;
    }, (err) => {
      //this.showMsg("相机异常")
    });
  }

  /**
   * 图片上传
   */
  upload() {
    const apiPath = ApiHost + "/api/forcedPhoto/savePhoto?token=" + localStorage.getItem("token");//接口地址
    let options: FileUploadOptions = {
      fileKey: 'file',
      fileName: 'name.jpg',   //文件名称
      headers: {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'//不加入 发生错误！！
      },
      // 如果要传参数，写这里
      params: {
        maxSize: 5000000,
        modularName: 'CNL',
        allowType: 'jpg',
        qrcode: this.qrcode,
        planPositionId: this.planPositionId,
        bizType: this.bizType
      }
    };
    let loader = this.loadingCtrl.create({
      content: "正在上传...",
    });
    loader.present();
    this.cutImageBase64(this.imgData, "100", "100", (newImgData) => {
      this.fileTransfer.upload(newImgData, apiPath, options).then((data) => {
        if (data.responseCode == 200) {
          this.photoNumber = this.photoNumber + 1;
          let result = JSON.parse(data.response);
          if (result.state) {
            this.disTag = true;
            loader.dismiss();
            this.showMsg(result.msg);
          } else {
            loader.dismiss();
            this.showMsg(result.msg);
          }
        } else {
          loader.dismiss();
          this.showMsg("系统异常");
        }
      }, (err) => {
        this.disTag = true;
        loader.dismiss();
        this.showMsg("服务器错误,请重新拍照上传");
      });
    });
  }

  //点击取消返回
  goBack() {
    this.navCtrl.pop();
  }

  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }



  cutImageBase64(base64: string, width: string, height: string, callback) {
    let newbase64: string;
    if (base64 == "assets/imgs/photo.jpg" || base64 == "") {
      newbase64 = "assets/imgs/photo.jpg";
      callback ? callback(newbase64) : null; //调用回调函数
    } else {
      let _img = new Image();
      _img.src = base64;
      _img.onload = function () {
        let _canvas = document.createElement("canvas");
        _canvas.setAttribute("width", width);
        _canvas.setAttribute("height", height);
        _canvas.getContext("2d").drawImage(_img, 0, 0, Number(width), Number(height));
        newbase64 = _canvas.toDataURL("image/jpeg");
        callback ? callback(newbase64) : null; //调用回调函数
      }
    }
  }


}
